package com.boxing.utils;

import com.boxing.bean.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCUtil {
    //驱动名称(包含了数据库的产品和数据库的版本号)
    private static String driver = "com.mysql.cj.jdbc.Driver";
    //数据库的url
    private static String url = "jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC";
    //数据库用户名
    private static String SQL_USER = "root";
    //数据库密码
    private static String  SQL_PSD = "12345678";

    static {
        //加载mysql驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //使用jdbc进行查询操作
    public static boolean queryUser(User user) throws Exception {
        //获取数据库连接
        Connection conn = DriverManager.getConnection(url,SQL_USER,SQL_PSD);
        //编写sql语句
        String sql = "select _name, _psd from t_user where _name='"+user.getUser()+"' and _psd='"+user.getPsd()+"'";
        //创建Statement
        Statement statement = conn.createStatement();
        //执行sql语句
        ResultSet set = statement.executeQuery(sql);
        System.out.println("执行querytUser sql成功");
        if (set != null && set.next()){
            //释放资源(建议先判断statement和conn是否为空再进行关闭)
            if(statement != null){
                statement.close();
            }
            if(conn != null){
                conn.close();
            }
            return true;
        }
        //释放资源(建议先判断statement和conn是否为空再进行关闭)
        if(statement != null){
            statement.close();
        }
        if(conn != null){
            conn.close();
        }
        return false;
    }

    //使用jdbc进行添加操作
    public static void insertUser(User user) throws Exception {
        //获取数据库连接
        Connection conn = DriverManager.getConnection(url,SQL_USER,SQL_PSD);
        //编写sql语句
        String sql = "insert into t_user(_name,_psd) values('"+user.getUser()+"','"+user.getPsd()+"')";
        //创建Statement
        Statement statement = conn.createStatement();
        //执行sql语句
        int count = statement.executeUpdate(sql);
        System.out.println("执行sql成功，一共影响了"+count+"条数据");
        //释放资源(建议先判断statement和conn是否为空再进行关闭)
        if(statement != null){
            statement.close();
        }
        if(conn != null){
            conn.close();
        }
    }

}
